package fw.asmx.appstoper;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.multidex.MultiDex;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import fw.asmx.appstoper.adapter.VPAdapter;
import fw.asmx.appstoper.adapter.item.AppItem;
import fw.asmx.appstoper.fragment.DataAppFragment;
import fw.asmx.appstoper.fragment.SystemAppFragment;
import fw.asmx.appstoper.utils.ShellUtils;

public class MainActivity extends AppCompatActivity
{
    private Toolbar toolbar;
    private TabLayout tabs;
    private ViewPager vp;
    private VPAdapter vpAdapter;

    private DataAppFragment daf;
    private SystemAppFragment saf;

    public List<AppItem> Datapps;
    public List<AppItem> Sysapps;
    public Map<String, Boolean> chkedMap;

    private ExecutorService exec;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        MultiDex.install(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("FW App Stopper");
        toolbar.inflateMenu(R.menu.menu_main_activity);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener()
        {
            @Override public boolean onMenuItemClick(MenuItem item)
            {
                switch (item.getItemId())
                {
                    case R.id.kill:
                        Toast.makeText(MainActivity.this, "XXXXXX", Toast.LENGTH_SHORT).show();
                        exec.execute(new Runnable()
                        {
                            @Override public void run()
                            {
                               stopApp();
                            }
                        });
                        break;
                }
                return true;
            }
        });
        exec = Executors.newCachedThreadPool();
        //
        exec.execute(new RootChkThread());
        exec.execute(new LoadAppsThread());
        //
        tabs = (TabLayout) findViewById(R.id.tabs);
        vp = (ViewPager) findViewById(R.id.vp);

        daf = new DataAppFragment();
        saf = new SystemAppFragment();
        vpAdapter = new VPAdapter(getSupportFragmentManager());
        vpAdapter.addFragment(daf, "用户应用");
        vpAdapter.addFragment(saf, "系统应用");
        vp.setAdapter(vpAdapter);

        tabs.setupWithViewPager(vp);
    }

    class LoadAppsThread implements Runnable
    {
        @Override public void run()
        {
            Datapps = new ArrayList<>();
            Sysapps = new ArrayList<>();
            //
            PackageManager m = getPackageManager();
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.addCategory(Intent.CATEGORY_LAUNCHER);
            List<PackageInfo> lst = m.getInstalledPackages(0);

            for (PackageInfo pi : lst)
            {
                if (pi.packageName.equals("fw.asmx.appstoper"))
                {
                    continue;
                }

                if ((pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0)
                {
                    AppItem ai = new AppItem(pi.applicationInfo.loadIcon(m), AppType.USER,
                                             pi.applicationInfo.loadLabel(m).toString(),
                                             pi.packageName);
                    Datapps.add(ai);
                }
                else
                {
                    AppItem ai = new AppItem(pi.applicationInfo.loadIcon(m), AppType.SYSTEM,
                                             pi.applicationInfo.loadLabel(m).toString(),
                                             pi.packageName);
                    Sysapps.add(ai);
                }
            }
            runOnUiThread(new Runnable()
            {
                @Override public void run()
                {
//                    daf.freshList();
//                    saf.freshList();
                }
            });
        }
    }

    class RootChkThread implements Runnable
    {
        @Override public void run()
        {
            if (!ShellUtils.checkRootPermission())
            {
                runOnUiThread(new Runnable()
                {
                    @Override public void run()
                    {
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("注意！")
                                .setMessage("本应用需要ROOT权限才能有效工作！")
                                .setNeutralButton("确定", null)
                                .show();
                    }
                });
            }
        }
    }

    @Override protected void onPause()
    {
        super.onPause();
        ShellUtils.execCommand("am force-stop " + getPackageName(), true, false);
    }

    private void stopApp()
    {
        List<String> al = new ArrayList<>();
        int ct = Datapps.size();
        for (int i = 0; i < ct; i++)
        {
            String s = Datapps.get(i).pkgName;
            if (chkedMap.get(s))
            {
                al.add("am force-stop " + s);
                //al.add("pm disable " + s);
                //al.add("pm enable " + s);
            }
        }
        ct = Sysapps.size();
        for (int i = 0; i < ct; i++)
        {
            String s = Sysapps.get(i).pkgName;
            if (chkedMap.get(s))
            {
                al.add("am force-stop " + s);
            }
        }

        String[] arr = new String[al.size()];
        al.toArray(arr);
        ShellUtils.CommandResult cr = ShellUtils.execCommand(arr, true);
        if (cr.result == 0)
        {
            ShellUtils.execCommand("am force-stop " + MainActivity.this.getPackageName(), true,
                                   false);
        }
        else
        {
            runOnUiThread(new Runnable()
            {
                @Override public void run()
                {
                    Toast.makeText(MainActivity.this, "部分应用结束失败！", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.kill:
                Toast.makeText(MainActivity.this, "XXXXXX", Toast.LENGTH_SHORT).show();
                exec.execute(new Runnable()
                {
                    @Override public void run()
                    {
                        stopApp();
                    }
                });
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
